package v1

import (
	"os"
	"tdy-backend/app/core"
	"tdy-backend/app/member/dto"
	"tdy-backend/app/member/model"
	"tdy-backend/app/member/service"
	"tdy-backend/global"
	"tdy-backend/pkg/storage/oss"
	"tdy-backend/pkg/storage/qiniu"
	"tdy-backend/utils"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

type UploaderController struct {
}

func (o *UploaderController) Execute(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["Upload"]

	filenames := []string{}
	uploadPath := global.TYD_CONFIG.GetString("file.uploadPath")
	for _, file := range files {
		unique := utils.CreateUniqueKey()
		path := uploadPath + cast.ToString(time.Now().Year()) + "/" + cast.ToString(int(time.Now().Month())) + "/" + cast.ToString(time.Now().Day()) + "/" + unique + "/"
		utils.CreateDir(path)
		filename := path + unique + "." + utils.GetFileExt(file.Filename)
		filenames = append(filenames, filename)
		// 上传文件至指定目录
		c.SaveUploadedFile(file, "./"+filename)
	}
	core.Ok(c, filenames, "上传成功")

}

// @Summary 新增媒体
// @Tags 管理端-媒体库
// @Param	Upload	formData	string true "上传参数"
// @Router /Uploader/Add [post]
func (o *UploaderController) Add(c *gin.Context) {
	logger := global.TYD_LOGGER
	db := global.TYD_DB
	token := c.Request.Header.Get("token")
	memberService := service.MemberService{}
	memberService.MakeORM(db)
	memberInfo, err := memberService.GetCurrentMemberInfo(token)
	if err != nil {
		core.CustomError(c, err.Error())
		return
	}
	form, _ := c.MultipartForm()
	files := form.File["Upload"]
	uploadPath := global.TYD_CONFIG.GetString("file.uploadPath")
	storageType := global.TYD_CONFIG.GetString("file.storage")
	uploaderService := service.UploaderService{}
	uploaderService.MakeORM(db).MakeMemberInfo(memberInfo)
	assetRow := []*model.Asset{}
	for _, file := range files {

		unique := utils.CreateUniqueKey()
		path := uploadPath + cast.ToString(time.Now().Year()) + "/" + cast.ToString(int(time.Now().Month())) + "/" + cast.ToString(time.Now().Day()) + "/"
		utils.CreateDir(path)
		filename := path + unique + "." + utils.GetFileExt(file.Filename)
		// 上传文件至指定目录
		c.SaveUploadedFile(file, "./"+filename)
		switch storageType {
		case "Qiniu":
			uploadInstance := qiniu.NewQiniu()
			uploadInstance.Upload(filename, filename)
			os.Remove(filename)
		case "Oss":
			uploadInstance := oss.NewOss()
			uploadInstance.Upload(filename, filename)
			os.Remove(filename)
		}
		asset, err := uploaderService.Add(file, filename)
		if err != nil {
			logger.Error(err.Error())
		}
		assetRow = append(assetRow, asset)
	}
	core.Ok(c, assetRow, "上传成功")
}

// @Summary 删除媒体
// @Tags 管理端-媒体库
// @Param       token	header string true "登录标识"
// @Param	body	body	dto.AssetDeleteDto true "删除参数"
// @Router /uploader/delete [post]
func (o *UploaderController) Delete(c *gin.Context) {
	var err error
	var param dto.AssetDeleteDto
	db := global.TYD_DB
	if err = c.ShouldBindJSON(&param); err != nil {
		core.CustomError(c, "参数缺失")
		return
	}
	token := c.Request.Header.Get("token")
	memberService := service.MemberService{}
	memberService.MakeORM(db)
	memberInfo, err := memberService.GetCurrentMemberInfo(token)
	if err != nil {
		core.CustomError(c, err.Error())
		return
	}
	uploaderService := service.UploaderService{}
	uploaderService.MakeORM(db).MakeMemberInfo(memberInfo)
	err = uploaderService.Delete(param)
	if err != nil {
		core.CustomError(c, err.Error())
		return
	}
	core.Ok(c, nil, "删除成功")
}

// @Summary 编辑媒体
// @Tags 管理端-媒体库
// @Param       token	header string true "登录标识"
// @Param	body	body	dto.AssetEditDto true "编辑参数"
// @Router /uploader/edit [post]
func (o *UploaderController) Edit(c *gin.Context) {
	var err error
	var param dto.AssetEditDto

	if err = c.ShouldBindJSON(&param); err != nil {
		core.CustomError(c, "参数缺失")
		return
	}
	db := global.TYD_DB
	token := c.Request.Header.Get("token")
	memberService := service.MemberService{}
	memberService.MakeORM(db)
	memberInfo, err := memberService.GetCurrentMemberInfo(token)
	if err != nil {
		core.CustomError(c, err.Error())
		return
	}
	uploaderService := service.UploaderService{}
	uploaderService.MakeORM(db).MakeMemberInfo(memberInfo)
	err = uploaderService.Edit(param)
	if err != nil {
		core.CustomError(c, err.Error())
		return
	}
	core.Ok(c, nil, "编辑成功")
}

// @Summary 分页媒体
// @Tags 管理端-媒体库
// @Param       token	header string true "登录标识"
// @Param	Page	query	uint false "页码"
// @Param	PageSize	query	uint false "页尺寸"
// @Param	Keyword	query	string false "搜索关键词"
// @Param	Type	query	int false "类型过滤  1图片2音频 3视频"
// @Router /Uploader/ListForPage [get]
func (o *UploaderController) ListForPage(c *gin.Context) {
	param := dto.AssetListDto{}
	c.Bind(&param)
	token := c.Request.Header.Get("token")
	db := global.TYD_DB
	memberService := service.MemberService{}
	memberService.MakeORM(db)
	memberInfo, err := memberService.GetCurrentMemberInfo(token)
	if err != nil {
		core.CustomError(c, err.Error())
		return
	}
	uploaderService := service.UploaderService{}
	uploaderService.MakeORM(db).MakeMemberInfo(memberInfo)
	data := uploaderService.ListForPage(param)
	core.Ok(c, data, "请求成功")
}
